<template>
  <div class="app-container">
    <h5 style="margin-top: 10px; font-size: 16px;">易购卡概况</h5>
    <div class="summary-cards">
      <el-card shadow="never" class="summary-card-item">
        <div class="card-title">易购卡数量</div>
        <div class="card-value">{{  cardSummary.pcCardNumber || 0 }}张</div>
      </el-card>
      <el-card shadow="never" class="summary-card-item">
        <div class="card-title">充值支付总额</div>
        <div class="card-value">¥{{ $amountUtils.getYuan(cardSummary.pcAmountPaid) || 0 }}</div>
      </el-card>
      <el-card shadow="never" class="summary-card-item">
        <div class="card-title">充值赠送总额</div>
        <div class="card-value">¥{{ $amountUtils.getYuan(cardSummary.pcTotalRechargeGift) || 0 }}</div>
      </el-card>
      <el-divider class="line-vertical" direction="vertical"></el-divider>
      <el-card shadow="never" class="summary-card-item">
        <div class="card-title">卡内总余额</div>
        <div class="card-value">¥{{ $amountUtils.getYuan(cardSummary.totalBalance) || 0 }}</div>
      </el-card>
      <el-card shadow="never" class="summary-card-item">
        <div class="card-title">实充余额</div>
        <div class="card-value">¥{{ $amountUtils.getYuan(cardSummary.pcActualBalance) || 0 }}</div>
      </el-card>
      <el-card shadow="never" class="summary-card-item">
        <div class="card-title">赠送余额</div>
        <div class="card-value">¥{{ $amountUtils.getYuan(cardSummary.pcGiftBalance) || 0 }}</div>
      </el-card>
    </div>


    <el-form :inline="true" :model="recordInfo.queryForm" class="demo-form-inline">
      <el-form-item label="卡号">
        <el-input v-model="recordInfo.queryForm.cardNumber" placeholder="卡号" clearable style="width: 200px;" />
      </el-form-item>

      <el-form-item label="会员手机">
        <el-input v-model="recordInfo.queryForm.mobile" @clear="clearMobile" placeholder="手机号" :maxlength="11"
          @input="handleMobileInput" clearable />
      </el-form-item>

      <el-form-item label="卡内余额">
        <el-select v-model="recordInfo.queryForm.hasBalance" clearable placeholder="卡内余额" style="width: 200px">
          <el-option v-for="item in hasBalanceList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="使用次数">
        <el-select v-model="recordInfo.queryForm.orderBy" clearable placeholder="使用次数" style="width: 200px">
          <el-option v-for="item in orderByList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>


      <OrganizationSelector
        v-model="organizationQuery"
        :user-type="userInfo.organizationType"
      />

      <!-- <el-form-item label="卡内余额">
        <el-input v-model="recordInfo.queryForm.minCardBalance" placeholder="最低金额" clearable style="width: 130px; margin-right: 5px;" />
        -
        <el-input v-model="recordInfo.queryForm.maxCardBalance" placeholder="最高金额" clearable style="width: 130px; margin-left: 5px;" />
      </el-form-item>

      <el-form-item label="使用次数">
        <el-input v-model="recordInfo.queryForm.minUseCount" placeholder="最小次数" clearable style="width: 130px; margin-right: 5px;" />
        -
        <el-input v-model="recordInfo.queryForm.maxUseCount" placeholder="最大次数" clearable style="width: 130px; margin-left: 5px;" />
      </el-form-item> -->

      <el-form-item label="办卡日期">
        <el-date-picker
          v-model="issueTimeValue"
          type="daterange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="defaultTime"
          @change="dateChange('issueTimeValue')"
          style="width: 300px"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- <div style="display: flex;justify-content: space-between;align-items: center; margin-bottom: 10px;">
      <h5 style="margin: 0; font-size: 16px;">易购卡列表</h5>
      <div class="statistics">
        <div class="statistics-item">
          易购卡：<span class="value">0张</span>
        </div>
        <div class="statistics-item">
          充值支付总额：<span class="value">￥0.00</span>
        </div>
        <div class="statistics-item">
          充值赠送总额：<span class="value">￥0.00</span>
        </div>
        <div class="statistics-item">
          卡内总余额：<span class="value">￥0.00</span>
        </div>
      </div>
    </div> -->
    <!-- <h5 style="margin-top: 10px; font-size: 16px;">易购卡列表</h5> -->
    <el-table
      v-loading="recordInfo.loading"
      class="table-default"
      :data="recordInfo.list"
      border
      style="width: 100%"
      max-height="600"
    >
      <el-table-column type="index" label="序号" width="60" align="center" />

      <el-table-column prop="memberCardId" width="180" label="卡号" align="center">
        <!-- <template slot-scope="scope">
          <el-button type="text" @click="goDetail(scope.row)">{{ scope.row.memberCardId }}</el-button>
        </template> -->
      </el-table-column>

      <el-table-column label="会员信息" width="220" align="center">
        <template slot-scope="scope">
          <div class="member-info-cell">
          <image-show :md5="scope.row.photoDownloadCode || ''" style="width:40px;height:40px;margin-right: 10px;" />
            <div class="member-text">
              <p class="name">{{ scope.row.userName }}</p>
              <p class="id-phone">ID: {{ scope.row.userId }}</p>
              <p class="id-phone">{{ scope.row.mobile }}</p>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="totalPaymentAmount" label="充值支付金额"  align="center" />
      <el-table-column prop="totalGiftAmount" label="充值赠送金额"  align="center" />
      <el-table-column prop="totalBalance" label="卡内金额" align="center" />
      <el-table-column prop="giftBalance" label="余额组成" width="120" align="center" >
        <template slot-scope="scope">
          <div style="white-space: pre-line;">实充{{scope.row.paymentBalance}}</div>
          <div style="white-space: pre-line;"> 赠送{{scope.row.giftBalance}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="usageCount" label="使用次数" align="center" />
      <el-table-column prop="createTime" label="办卡日期" align="center" />
      <el-table-column prop="headquartersName" label="所属总部" width="150" align="center"  />
      <el-table-column prop="chainName" label="所属连锁" width="150" align="center"  />
      <el-table-column prop="organizationName" label="所属门店" width="150" align="center"  />

      <!-- <el-table-column label="操作" fixed="right" width="80" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="goDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination
      v-show="recordInfo.total > 0"
      :total="recordInfo.total"
      :page.sync="recordInfo.queryForm.page"
      :limit.sync="recordInfo.queryForm.pageSize"
      @pagination="getRecordList"
      :page-sizes="[10, 20, 50, 100]"
    >
       <!-- <div slot="total" class="pagination-summary">
        易购卡数<span class="value">{{ recordInfo.total }}张</span> |
        充值支付总额<span class="value">¥{{ cardSummary.totalPaidAmount }}</span> |
        充值赠送总额<span class="value">¥{{ cardSummary.totalGiftAmount }}</span> |
        卡内总余额<span class="value">¥{{ cardSummary.totalCardBalance }}</span>
      </div> -->
    </pagination>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import filters from '@/filters/index'
import ListMixin from '@/mixins/modules/list'
import messageMixin from '@/mixins/modules/message'
import Pagination from '@/components/Pagination'
import OrganizationSelector from '@/views/member/components/OrganizationSelector.vue'
import imageShow from '@/components/imageShow'

export default {
  components: {
    Pagination,
    imageShow,
    OrganizationSelector
  },
  filters: { ...filters },
  mixins: [ListMixin, messageMixin],
  data() {
    return {
      // 绑定到日期选择器的值
      issueTimeValue: null,

      cardSummary: {},

      recordInfo: {
        queryForm: {
          page: 1,
          pageSize: 10,
          hasBalance: '', // 是否有余额(true 有余额 false 无余额)
          orderBy: '',  // highFrequency（使用次数从高到低）lowFrequency（使用次数从低到高）
          // 查询表单字段
          cardNumber: '',
          mobile: '',
          returnCount: true,
          userId: '',
          memberKeyword: '',
          minCardBalance: '', // 卡内余额最低
          maxCardBalance: '', // 卡内余额最高
          minUseCount: '',    // 使用次数最低
          maxUseCount: '',    // 使用次数最高
          headquartersId: '',
          chainId: '',
          storeId: '',
        },
        requestUrl: this.$api.getMemberCardList, // 假设存在易购卡列表接口
        list: [],
        total: 0, // 初始总数
        loading: false
      },
      orderByList: [
        { name: '使用次数从高到低', value: 'highFrequency' },
        { name: '使用次数从低到高', value: 'lowFrequency' }
      ],
      hasBalanceList: [
        { name: '可用余额大于0', value: true },
        { name: '可用余额等于0', value: false }
      ],
      // 静态数据列表（实际项目可能从 Vuex 或 API 获取）
      storeList: [{ name: '万达店', value: 1 }, { name: '东街口店', value: 2 }, { name: '总部', value: 3 }],
      // **关键配置**：告知 Mixin 哪些字段需要进行日期转换
      changeDateNameInfo: {
        issueTimeValue: ['cardStartTime', 'cardEndTime']
      },
      getListCallback: (res) => {
        // 假设 API 返回的 res 中包含统计数据，例如 res.summary
        // if (res.summary) {
        //   this.cardSummary = res.summary
        // }

        if (res.list && res.list.length > 0) {
          res.list.forEach(item => {
            // 1. 格式化时间
            item.createTime = this.$commonUtils.getShowTime(item.createTime) // 办卡日期

            // 2. 格式化金额
            item.totalPaymentAmount =  '¥' +this.$amountUtils.getYuan(item.totalPaymentAmount)
            item.totalGiftAmount = '¥' + this.$amountUtils.getYuan(item.totalGiftAmount)
            item.totalBalance = '¥' + this.$amountUtils.getYuan(item.totalBalance)
            item.paymentBalance = '¥' + this.$amountUtils.getYuan(item.paymentBalance)
            item.giftBalance ='¥' + this.$amountUtils.getYuan(item.giftBalance)
            item.usageCount = item.usageCount + '次' // 格式化使用次数

            // 3. 模拟会员信息
            if (!item.memberAvatar) {
              item.memberAvatar = '/static/default-avatar.png'
            }
          })
        }
        // 更新列表和总数
        this.recordInfo.list = res.list || []
        // Mixin 默认会处理总数 this.recordInfo.total = Number(res.count)
      },

      // 覆盖 Mixin 的 beforeRequest
      beforeRequest: () => {
        // 办卡日期范围处理
        this.changeDate(this.issueTimeValue, 'issueTimeValue')

        // 确保 returnCount 逻辑正确
        this.recordInfo.queryForm.returnCount = this.recordInfo.queryForm.page === 1

        // 不返回 false，表示继续请求
      }
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ]),
    organizationQuery: {
      get() {
        return {
          headquartersId: this.recordInfo.queryForm.headquartersId,
          chainId: this.recordInfo.queryForm.chainId,
          storeId: this.recordInfo.queryForm.storeId,
        };
      },
      set(newVal) {
        this.recordInfo.queryForm.headquartersId = newVal.headquartersId;
        this.recordInfo.queryForm.chainId = newVal.chainId;
        this.recordInfo.queryForm.storeId = newVal.storeId;
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.getCardSummary()
    },
    getCardSummary() {
      let params = {}
      if (this.userInfo.organizationType === 1) {
        // 总部用户
        params.headquartersId = this.userInfo.organizationId
      } else if (this.userInfo.organizationType === 4) {
        // 连锁用户
        params.chainId = this.userInfo.organizationId
      } else if (this.userInfo.organizationType === 5) {
        // 门店用户
        params.storeId = this.userInfo.organizationId
      }
      this.$api.getCardOverview(params).then(res => {
        console.log('card overview:', res)
        this.cardSummary = res
      })
    },

    clearMobile() {
      this.recordInfo.queryForm.mobile = '';
      this.recordInfo.queryForm.userId = '';
    },
    handleMobileInput(value) {
      const mobileNumber = value.trim();
      if (mobileNumber.length === 11) {
        console.log('手机号大于七位，触发查询请求:', mobileNumber);
        this.$api.getMemberInfoList({
          returnUserDetail: true,
          returnCount: false,
          orderBy: 'createTimeDesc',
          mobile: mobileNumber,
          pageSize: 100,
          page: 1
        }).then(response => {
          console.log('查询结果:', response.list);
          if (response.list && response.list.length > 0) {
            this.recordInfo.queryForm.userId = response.list[0].userId;
          }else{
            this.recordInfo.queryForm.userId = '999999999'; // 设置一个不存在的用户ID，确保查询无结果
          }
          // 处理查询结果
        })
          .catch(error => {
            console.error('查询出错:', error);
          });
      }
    },
    // 查询按钮，利用 Mixin 的 getRecordList
    search() {
      this.recordInfo.queryForm.page = 1
      this.getRecordList()
    },

    // 重置表单，清空所有查询条件
    resetForm() {
      // 业务字段清空
      this.recordInfo.queryForm = {
        page: 1,
        pageSize: 10,
        orderBy: '',
        memberCardId: '',
        memberKeyword: '',
        minCardBalance: '',
        maxCardBalance: '',
        minUseCount: '',
        maxUseCount: '',
        headquartersId: '', // 清空
    chainId: '',        // 清空
    storeId: '',        // 清空
      }
      // 日期清空
      this.issueTimeValue = null
      // 重新查询
      this.search()
    },

    // 查看易购卡详情 (跳转新 Tab)
    goDetail(item) {
      this.$addTab('memberCardDetail', {
        memberCardId: item.memberCardId
      }, '易购卡详情 - ' + item.memberCardId)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

/* --- 顶部统计卡片样式 --- */
.summary-cards {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  .line-vertical {
    height: auto;
    margin: 0 10px;
  }
  .summary-card-item {
    flex: 1;
    margin: 0 10px;
    background-color: #f7f9fa;
    border: none;

    &:last-child {
      margin-right: 0;
    }

    ::v-deep .el-card__body {
      padding: 15px;
    }

    .card-title {
      font-size: 14px;
      color: #909399;
      margin-bottom: 5px;
    }
    .card-value {
      font-size: 24px;
      font-weight: bold;
      color: #303133;
      // 突出金额部分
      &:nth-child(2), &:nth-child(3), &:nth-child(4) {
        color: #F07505; // 沿用你代码中的主题色
      }
    }
  }
}

/* --- 查询表单样式 --- */
.demo-form-inline {
  padding-bottom: 5px;
  .el-form-item {
    margin-right: 15px;
    margin-bottom: 10px;
  }
}

/* --- 表格样式 --- */

// 表格内会员信息单元格样式（沿用）
.member-info-cell {
  display: flex;
  align-items: center;
  .avatar-sm {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 8px;
    object-fit: cover;
    border: 1px solid #eee;
  }
  .member-text {
    text-align: left;
    p {
      margin: 0;
      line-height: 1.2;
    }
    .name {
      font-weight: bold;
      color: #333;
    }
    .id-phone {
      font-size: 12px;
      color: #999;
    }
  }
}

// 使金额列右对齐
::v-deep .el-table {
    // 充值支付金额 (第4列), 充值赠送金额 (第5列), 卡内金额 (第6列), 退款金额 (第7列)
    .el-table__cell:nth-child(4),
    .el-table__cell:nth-child(5),
    .el-table__cell:nth-child(6),
    .el-table__cell:nth-child(7) {
        .cell {
            text-align: right;
        }
    }
}

/* --- 分页底部统计样式 --- */
.pagination-summary {
  display: inline-block;
  margin-right: 20px;
  font-size: 14px;
  color: #606266;

  .value {
    color: #F07505;
    font-weight: bold;
    margin: 0 5px;
  }
}

// 统计信息样式
.statistics {
  display: flex;
  justify-content: flex-end;
  font-size: 14px;
  color: #606266;

  .statistics-item {
    margin-left: 20px;
  }

  .value {
    color: #F07505; // 采用你之前代码中的高亮色
    font-weight: bold;
    font-size: 16px;
  }
}
</style>
